package br.gendi.dialog;

import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import au.id.jericho.lib.html.Source;

public class VisualizadorConsol implements IVisualizador {


	private Shell sShell = null;

	private ScrolledComposite scrolledComposite = null;
	private Composite composite = null;
	private Table table = null;
	private int total = 0;
	private ArrayList<Table> listaTabelas = new ArrayList<Table>();
	private Color defBgColor = null;


	private void createScrolledComposite() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;
		scrolledComposite = new ScrolledComposite(sShell, SWT.NONE);
		scrolledComposite.setLayout(new FillLayout());
		scrolledComposite.setAlwaysShowScrollBars(true);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		createComposite();
		scrolledComposite.setLayoutData(gridData);
		scrolledComposite.setContent(composite);
	}

	private void createComposite() {
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.horizontalSpacing = 2;
		gridLayout1.marginWidth = 2;
		gridLayout1.marginHeight = 2;
		gridLayout1.verticalSpacing = 2;
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.grabExcessVerticalSpace = true;
		gridData2.verticalAlignment = GridData.FILL;
		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.verticalAlignment = GridData.FILL;
		composite = new Composite(scrolledComposite, SWT.NONE);
		composite.setLayout(gridLayout1);

	}

	@Override
	public void adicionar(final String nome, final String html) throws Exception {

		total+=1;
		if (total%3 == 0) {
			createScrolledComposite();
		}
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.horizontalSpacing = 2;
		gridLayout1.marginWidth = 2;
		gridLayout1.marginHeight = 2;
		gridLayout1.verticalSpacing = 2;

		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.heightHint = 200;
		gridData1.verticalAlignment = GridData.FILL;

		Label a = new Label(composite, SWT.NONE);
		a.setText(nome);

		table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLayoutData(gridData1);
		table.setLinesVisible(true);
		if (defBgColor == null)
			defBgColor = table.getBackground();

		ArrayList<String> l = new ArrayList<String>();
		ArrayList<String> linhasTabela = new ArrayList<String>();
		int maior = 0;
		String tmp = null;
		String[] stringTab = null;
		String tmpTab[] = null;


		Source source=new Source(html);
		String renderedText=source.getRenderer().toString();
		String[] linhas = renderedText.split("\n");

		//removendo linhas vazias
		for (int i=0; i< linhas.length; i++) {
			if (linhas[i].trim().length() > 0)
				l.add(linhas[i]);
		}

		//verificando qual a linha com maior numero de \t
		//para ser as linhas que vão para a Table
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");
				if (stringTab.length > maior)
					maior = stringTab.length;
			} 
		}


		//passando as informações nos seus devidos locais.
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");

				if (stringTab.length == maior) {
					linhasTabela.add(tmp);
				} else {

				}
			} else {

			}
		}

		//sourcesTabela.put(nome, linhasTabela);

		//adicionando as tabelas.
		for (int i=0;i<linhasTabela.size(); i++) {
			tmp = linhasTabela.get(i);
			tmpTab = tmp.split("\t");

			if (i==0) {
				for (int j=0; j<tmpTab.length; j++) {
					TableColumn column = new TableColumn (table, SWT.NONE);
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					column.setText(tmpTab[j]);
				}
			} else {
				final TableColumn [] columns = table.getColumns ();
				TableItem item = new TableItem (table, SWT.NONE);
				for (int j=0; j<columns.length; j++) {
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					item.setText (j, tmpTab[j]);
				}
			}
		}

		final TableColumn [] columns = table.getColumns();
		for (int i=0; i<columns.length; i++) 
			columns[i].pack();

		table.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				Table t = (Table)arg0.widget;
				String campo = "";
				boolean tudoCarac = true;
				int coluna=-1;
				int maiorTamanho = -1;
				for (int i=0; i<t.getColumnCount();i++) {
					tudoCarac = true;
					campo = t.getItem(t.getSelectionIndex()).getText(i);
					campo = campo.replaceAll("\t", "").replaceAll(" ", "").trim();
					for (int j=0;j<campo.length();j++)
						if (Character.isLetter(campo.charAt(j)) == false)
							tudoCarac = false;

					if (tudoCarac == true)
						if (campo.length() >= maiorTamanho) {
							maiorTamanho = campo.length();
							coluna = i;
						}
				}
				String txtSelecionado = t.getItem(t.getSelectionIndex()).getText(coluna).replaceAll("\t", "").replaceAll(" ", "").trim();;
				//System.out.println("--> "+txtSelecionado);
				buscarEmOutrasTabelas(t, txtSelecionado);
			}
		});
		listaTabelas.add(table);
		
Rectangle pDisplayBounds = sShell.getDisplay().getBounds();
		
        // Set Width and Height(doesn't matter value)
		int nMinWidth = pDisplayBounds.width  / 2;
		int nMinHeight = pDisplayBounds.height / 2;

         // This formulae calculate the shell's Left ant Top
		int nLeft = (pDisplayBounds.width - nMinWidth) / 2;
		int nTop = (pDisplayBounds.height - nMinHeight) / 2;
              
          // Set shell bounds,
		sShell.setBounds(nLeft, nTop, nMinWidth, nMinHeight);
		
		sShell.pack();
		if (!sShell.isVisible())
			sShell.open();

	}

	private void buscarEmOutrasTabelas(Table tabela, String txtSelecionado) {
		//remover selecao de todas as outras tabelas
		Table tbl = null;
		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			if (tbl != tabela)
				tbl.deselectAll();
		}

		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			for (int k=0; k<tbl.getItemCount(); k++)
				for (int j=0; j<tbl.getColumnCount();j++)
					tbl.getItem(k).setBackground(defBgColor);
		}

		//pesquisar em cada coluna.
		String campo="";
		for (int i=0;i<listaTabelas.size();i++) {
			tbl = listaTabelas.get(i);
			for (int k=0; k<tbl.getItemCount(); k++)
				for (int j=0; j<tbl.getColumnCount();j++) {

					campo = tbl.getItem(k).getText(j);
					campo = campo.replaceAll("\t", "").replaceAll(" ", "").trim();
					if (campo.equals(txtSelecionado)) {
						tbl.getItem(k).setBackground(new Color(sShell.getDisplay(), 255,150,80));
					}
				}
		}

	}

	public VisualizadorConsol() {
		super();
		createSShell();
	}

	//	/**
	//	 * @param args
	//	 */
	//	public static void main(String[] args) {
	//		// TODO Auto-generated method stub
	//		/* Before this is run, be sure to set up the launch configuration (Arguments->VM Arguments)
	//		 * for the correct SWT library path in order to run with the SWT dlls. 
	//		 * The dlls are located in the SWT plugin jar.  
	//		 * For example, on Windows the Eclipse SWT 3.1 plugin jar is:
	//		 *       installation_directory\plugins\org.eclipse.swt.win32_3.1.0.jar
	//		 */
	//		Display display = Display.getDefault();
	//		VisualizadorConsol thisClass = new VisualizadorConsol();
	//		thisClass.createSShell();
	//		thisClass.sShell.open();
	//
	//		while (!thisClass.sShell.isDisposed()) {
	//			if (!display.readAndDispatch())
	//				display.sleep();
	//		}
	//		display.dispose();
	//	}

	/**
	 * This method initializes sShell
	 */
	private void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.numColumns = 2;
		gridLayout.verticalSpacing = 2;
		sShell = new Shell();
		sShell.setText("Resultados - Consolidador");
		sShell.setSize(new Point(800, 600));
		sShell.setLayout(gridLayout);
		ImageData isLarge = br.gendi.rcp.Activator.getImageDescriptor("/icons/mainicon32.png").getImageData();
		ImageData isSmall = br.gendi.rcp.Activator.getImageDescriptor("/icons/mainicon16.png").getImageData();

		Image large = new Image(sShell.getDisplay(), isLarge);
		Image small = new Image(sShell.getDisplay(), isSmall);

		sShell.setImages(new Image[] {small, large});
		createScrolledComposite();
		//		try {
		//		adicionar("epij","data/epij.txt.html");
		//		adicionar("rankpep","data/rankpep.html");
		//		adicionar("syfpeithi","data/syfpeithi.html");
		//		adicionar("hlabind", "data/hlabind.html");
		//		adicionar("hlabind2", "data/hlabind.html");
		//	} catch (Exception e) {
		//		e.printStackTrace();
		//	}
	}


}
